package com.anji.sp.push.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.anji.sp.enums.IsDeleteEnum;
import com.anji.sp.enums.RepCodeEnum;
import com.anji.sp.enums.UserStatus;
import com.anji.sp.model.ResponseModel;
import com.anji.sp.model.po.SpApplicationPO;
import com.anji.sp.push.constants.MqConstants;
import com.anji.sp.push.mapper.PushConfiguresMapper;
import com.anji.sp.push.model.po.PushConfiguresPO;
import com.anji.sp.push.model.vo.PushConfiguresVO;
import com.anji.sp.push.model.vo.PushMessageVO;
import com.anji.sp.push.model.vo.PushUserVO;
import com.anji.sp.push.model.vo.RequestSendBean;
import com.anji.sp.push.service.PushConfiguresService;
import com.anji.sp.push.service.PushMessageService;
import com.anji.sp.push.service.PushUserService;
import com.anji.sp.service.SpApplicationService;
import com.anji.sp.util.BeanUtils;
import com.anji.sp.util.SnowflakeUtils;
import com.anji.sp.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.annotations.ApiOperation;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 推送配置项 服务实现类
 * </p>
 *
 * @author kean
 * @since 2021-01-20
 */
@Service
public class AJPushSendService {
    @Autowired
    private AmqpTemplate template;
    @Autowired
    private PushMessageService pushMessageService;
    @Autowired
    private PushUserService pushUserService;
    @Autowired
    private PushConfiguresService pushConfiguresService;
    @Autowired
    private SpApplicationService applicationService;

    public ResponseModel init(PushUserVO pushUserVO) {
        return pushUserService.initUserInfo(pushUserVO);
    }
    public ResponseModel pushBatch(RequestSendBean requestSendBean) {
        if (StringUtils.isEmpty(requestSendBean.getPushType())){
            requestSendBean.setPushType("0");
        }
        //todo
        // 1、拿到数据
        if (requestSendBean == null) {
            return RepCodeEnum.NULL_ERROR.parseError("参数");
        }
        if (StringUtils.isEmpty(requestSendBean.getAppKey())) {
            return RepCodeEnum.NULL_ERROR.parseError("AppKey");

        }
        if (StringUtils.isEmpty(requestSendBean.getTitle())) {
            return RepCodeEnum.NULL_ERROR.parseError("标题");
        }
        if (StringUtils.isEmpty(requestSendBean.getContent())) {
            return RepCodeEnum.NULL_ERROR.parseError("内容");
        }
        if (requestSendBean.getDeviceIds() == null || requestSendBean.getDeviceIds().size() == 0) {
            return RepCodeEnum.NULL_ERROR.parseError("deviceId");
        }
        ResponseModel responseModel = beforePush(requestSendBean);
        // 7、保存成功发送消息给消费者消费
        if (responseModel.isSuccess()) {
            PushMessageVO vo = new PushMessageVO();
            BeanUtils.copyProperties(responseModel.getRepData(), vo);
            //推送消息
            template.convertAndSend(MqConstants.directBatchQueue, vo);
            // 8、将msgId及消息类型回调给用户方
            Map m = new HashMap();
            m.put("msgId", vo.getMsgId());
            m.put("appKey", vo.getAppKey());
            return ResponseModel.successData(m);
        } else {
            return responseModel;
        }

    }

    public ResponseModel pushAll(RequestSendBean requestSendBean) {
        if (StringUtils.isEmpty(requestSendBean.getPushType())){
            requestSendBean.setPushType("0");
        }
        // 1、拿到数据
        if (requestSendBean == null) {
            return ResponseModel.errorMsg("参数不能为空");
        }
        if (StringUtils.isEmpty(requestSendBean.getAppKey())) {
            return ResponseModel.errorMsg("请输入AppKey");
        }
        if (requestSendBean.getPushType().equals("0") && StringUtils.isEmpty(requestSendBean.getTitle())) {
            return ResponseModel.errorMsg("请输入标题");
        }
        if (StringUtils.isEmpty(requestSendBean.getContent())) {
            return ResponseModel.errorMsg("请输入内容");
        }
        ResponseModel responseModel = beforePush(requestSendBean);
        // 7、保存成功发送消息给消费者消费
        if (responseModel.isSuccess()) {
            PushMessageVO vo = new PushMessageVO();
            BeanUtils.copyProperties(responseModel.getRepData(), vo);
            //推送全推消息
            template.convertAndSend(MqConstants.directAllQueue, vo);
            // 8、将msgId及消息类型回调给用户方
            Map m = new HashMap();
            m.put("msgId", vo.getMsgId());
            m.put("appKey", vo.getAppKey());
            return ResponseModel.successData(m);
        } else {
            return responseModel;
        }
    }

    /**
     * 拿到参数后处理下
     *
     * @param requestSendBean
     * @return
     */
    private ResponseModel beforePush(RequestSendBean requestSendBean) {
        if (requestSendBean.getSendOrigin().equals("1")){
            if (StringUtils.isBlank(requestSendBean.getSecretKey())){
                return RepCodeEnum.NULL_ERROR.parseError("secretKey");
            }
            PushConfiguresVO pushConfiguresVO = new PushConfiguresVO();
            pushConfiguresVO.setAppKey(requestSendBean.getAppKey());
            pushConfiguresVO.setSecretKey(requestSendBean.getSecretKey());
            ResponseModel selectResponse = pushConfiguresService.selectOne(pushConfiguresVO);
            PushConfiguresVO pushConfigures = (PushConfiguresVO) selectResponse.getRepData();
            if (Objects.isNull(pushConfigures)){
                return RepCodeEnum.NOT_EXIST_ERROR.parseError("应用推送配置");
            }
        }
        // 2、转换数据为 json 字符串
        String operParam = JSONObject.toJSONString(requestSendBean);

        String msgId = SnowflakeUtils.getId();
        // 3、new PushMessageVO() 将 msgid 存入PushMessageVO
        PushMessageVO pushMessageVO = new PushMessageVO();
        pushMessageVO.setMsgId(msgId);
        pushMessageVO.setAppKey(requestSendBean.getAppKey());
        // 4、将json 存入operParam
        pushMessageVO.setOperParam(operParam);
        pushMessageVO.setPushType(requestSendBean.getPushType());
        pushMessageVO.setSendOrigin(requestSendBean.getSendOrigin());
        // 5、设置consumptionState 为0 默认未0  可以不设置
        // 6、保存数据库
        ResponseModel responseModel = pushMessageService.create(pushMessageVO);
        return responseModel;
    }

    public ResponseModel queryHistory(@RequestBody PushMessageVO pushMessageVO) {
        return pushMessageService.queryAmountByMsgId(pushMessageVO);
    }
}
